<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Cookie切换
 *
 * @author 	FangMinglong
 * @date 	2017-04-14 16:20
 */
class Lib_cookie
{

	protected $CI;

	public function __construct()
	{
		$this->CI =& get_instance();
		$this->CI->config->load('cookie');
		$this->CI->load->helper('cookie');
	}

	/**
	 * 设置语言
	 *
	 * @desc 核心代码不要参与太多默认行为定义！
	 * @param string $language 语言，不要有默认值！
	 * @param number $expire   有效期（秒），默认31天，可以给定一个默认值。
	 * @return void
	 */
	public function set_language($language, $expire = /*86400 * 31*/2678400)
	{
		$key = $this->CI->config->item('language_key');
		set_cookie($key, $language, $expire);
	}
	
	public function get_language()
	{
		$key = $this->CI->config->item('language_key');
		// TODO TMP: 基类中 COOKIE set_language 后并不能立即生效！COOKIE get_language 可先去取 $this->language，立即生效！
		if (!empty($this->CI->language) && !empty($this->CI->haveNewCookieLanguage)) return $this->CI->language;
		return get_cookie($key);
	}
	
	// 当前币种
	public function set_currency($currency, $expire = /*86400 * 31*/2678400)
	{
		$key = $this->CI->config->item('currency_key');
		set_cookie($key, $currency, $expire);
	}
	
	public function get_currency()
	{
		$key = $this->CI->config->item('currency_key');
		// TODO TMP DEALING
		$currency = get_cookie($key);
		
		# $this->CI->config->load('language', !true);
		$currency_mapper = $this->CI->config->item('supported_currencies', 'multi_currency');
		$currency_list = array_keys($currency_mapper);
		if (in_array($currency, $currency_list)) {
			return $currency;
		}
		
		# $default = 'USD';
		# $default = $this->CI->config->item('language');
		$default = current($currency_list);
		$this->set_currency($default);
		
		return $default;
	}
	
	// 当前时区
	public function set_timezone($timezone, $expire = /*86400 * 31*/2678400)
	{
		$key = $this->CI->config->item('timezone_key');
		set_cookie($key, $timezone, $expire);
	}
	
	public function get_timezone()
	{
		$key = $this->CI->config->item('timezone_key');
		$timezone = get_cookie($key);
		
		$timezone_list = array_keys($this->CI->config->item('supported_timezones', 'multi_timezone'));
		if (in_array($timezone, $timezone_list)) {
			return $timezone;
		}
		
		$default = current($timezone_list);
		$this->set_timezone($default);
		
		return $default;
	}
	
	/**
	 * 设置登录Token
	 * 
	 * @param string $token
	 * @param number $expire
	 */
	public function set_token($token, $expire = /*86400 * 31*/2678400)
	{
		$key = $this->CI->config->item('token_key');
		set_cookie($key, $token, $expire);
	}
	
	public function get_token()
	{
		$key = $this->CI->config->item('token_key');
		return get_cookie($key);
	}
}